<?php

namespace XsKit\Activitylog;

use Carbon\Carbon;
use Hyperf\Command\Command;
use Hyperf\Database\Query\Builder;

class CleanActivitylogCommand extends Command
{
    protected $signature = 'activitylog:clean
                            {log? : (optional) The log name that will be cleaned.}
                            {--days= : (optional) Records older than this number of days will be cleaned.}';

    protected $description = 'Clean up old records from the activity log.';

    public function handle()
    {
        try {
            $this->comment('Cleaning activity log...');

            $log = $this->input->getArgument('log');

            $maxAgeInDays = $this->input->getOption('days') ?? config('activitylog.delete_records_older_than_days');

            $cutOffDate = Carbon::now()->subDays($maxAgeInDays)->format('Y-m-d H:i:s');

            $activity = ConfigProvider::getActivityModelInstance();

            $amountDeleted = $activity::where('created_at', '<', $cutOffDate)
                ->when($log !== null, function (Builder $query) use ($log) {
                    $query->inLog($log);
                })
                ->delete();

            $this->info("Deleted {$amountDeleted} record(s) from the activity log.");

            $this->comment('All done!');
        } catch (\Throwable $e) {
            $this->error($e->getMessage() . 'from the activity log.');
        }
    }
}
